import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import 'package:situation/app/theme/gaps.dart';

class MapPolygonDraw extends StatefulWidget {
  const MapPolygonDraw({
    super.key,
    this.onSave, // 新增保存回调
    this.onPolygonsChanged,
    this.polygonColor = Colors.blue,
    this.borderWidth = 3.0,
    this.fillOpacity = 0.3,
  });

  final ValueChanged<List<List<LatLng>>>? onPolygonsChanged;
  final Function(List<LatLng>)? onSave; // 新增
  final Color polygonColor;
  final double borderWidth;
  final double fillOpacity;

  static late final GlobalKey<_MapPolygonDrawState> stateKey =
      GlobalKey<_MapPolygonDrawState>();

  static void startNewPolygon() => stateKey.currentState?._startNewPolygon();
  static void undoPoint() => stateKey.currentState?._undoPoint();
  static void completePolygon() => stateKey.currentState?._completePolygon();
  static void addPoint(LatLng point) => stateKey.currentState?._addPoint(point);
  static void removeAll() => stateKey.currentState?._removeAll();

  @override
  State<MapPolygonDraw> createState() => _MapPolygonDrawState();
}

class _MapPolygonDrawState extends State<MapPolygonDraw> {
  final List<List<LatLng>> _polygons = [];
  List<LatLng> _currentPolygon = [];
  bool _isDrawing = false;

  // 添加临时面存储
  List<LatLng> _tempPolygon = [];

  void _removeAll () {
    setState(() {
      _polygons.clear();
      _currentPolygon.clear();
      _tempPolygon.clear();
      _isDrawing = false;
    });
  }

  void _startNewPolygon() {
    setState(() {
      _isDrawing = true;
      _currentPolygon = [];
      _tempPolygon = []; // 重置临时面
    });
  }

  void _addPoint(LatLng point) {
    if (!_isDrawing) return;

    setState(() {
      _currentPolygon.add(point);

      // 实时生成闭合面（当点数≥3时）
      _tempPolygon = _currentPolygon.length >= 3
          ? [..._currentPolygon, _currentPolygon.first]
          : [];
    });
  }

  void _undoPoint() {
    if (_currentPolygon.isEmpty) return;

    setState(() {
      _currentPolygon.removeLast();

      // 新增：更新临时面数据
      _tempPolygon = _currentPolygon.length >= 3
          ? [..._currentPolygon, _currentPolygon.first]
          : [];

      // 新增：同步清理已完成的面数据
      if (_currentPolygon.isEmpty) {
        _isDrawing = false;
        _polygons.removeWhere((polygon) =>
        polygon.length == _tempPolygon.length
        );
      }
    });
  }

  // 修改2：调整completePolygon方法

  void _completePolygon() {
    if (_currentPolygon.length < 3) return;

    widget.onSave?.call(_currentPolygon);
    setState(() {
      _polygons.add([..._currentPolygon, _currentPolygon.first]);
      _currentPolygon.clear();
      _tempPolygon.clear();
      _isDrawing = false;
    });
    widget.onPolygonsChanged?.call(_polygons);

  }
  // 修改3：添加临时线存储
  final List<List<LatLng>> _lines = [];

  Widget _buildControlPanel() {
    return Positioned(
      right: 20,
      bottom: Get.height * 0.4,
      child: Container(
        padding: _isDrawing ? const EdgeInsets.all(8) :const EdgeInsets.all(0),
        decoration: BoxDecoration(
          color: Colors.black.withAlpha(80),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          children: [
            if (_isDrawing) ...[
              _buildIconButton(
                icon: Icons.save,
                color: Colors.green,
                onPressed: _completePolygon,
              ),
              Gaps.vGap8,
              _buildIconButton(
                icon: Icons.undo,
                color: Colors.orange,
                onPressed: _undoPoint,
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildIconButton({
    required IconData icon,
    required Color color,
    required VoidCallback onPressed,
  }) {
    return GestureDetector(
      onTap: onPressed,
      child: Container(
        padding: const EdgeInsets.all(6),
        decoration: const BoxDecoration(
          color: Colors.white,
          shape: BoxShape.circle,
        ),
        child: Icon(icon, size: 20, color: color),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 实时预览面
        PolygonLayer(
          polygons: [
            if (_tempPolygon.isNotEmpty)
              Polygon(
                points: _tempPolygon,
                color: widget.polygonColor.withOpacity(0.2), // 半透明预览
                borderColor: widget.polygonColor.withAlpha(100),
                borderStrokeWidth: widget.borderWidth,
              ),
          ],
        ),

        // 已完成的面
        PolygonLayer(
          polygons: [
            for (final polygon in _polygons)
              Polygon(
                points: polygon,
                color: widget.polygonColor.withOpacity(widget.fillOpacity),
                borderColor: widget.polygonColor,
                borderStrokeWidth: widget.borderWidth,
              ),
          ],
        ),

        // 当前正在绘制的临时边线
        if (_currentPolygon.length >= 2)
          PolylineLayer(
            polylines: [
              Polyline(
                points: _currentPolygon,
                color: widget.polygonColor.withAlpha(150),
                strokeWidth: widget.borderWidth,
              ),
            ],
          ),

        // 绘制中的标记点
        MarkerLayer(
          markers: [
            if (_isDrawing)
              for (final point in _currentPolygon)
                Marker(
                  width: 20,
                  height: 20,
                  point: point,
                  child: const Icon(Icons.circle, size: 20, color: Colors.blue),
                ),
          ],
        ),

        _buildControlPanel(),
      ],
    );
  }
}
